<template>
  <div class="editItem">
    <!-- 回填或新增 -->
    <div class="head">
      <NavBar
        @goBack="goBack"
        :title="title"
      ></NavBar>
    </div>
    <div class="content">
      <van-field
        class="name"
        v-model="name"
        label="Name"
        placeholder="Please enter the name"
      />
      <van-field
        class="name"
        v-model="phone"
        label="Mobile Phone"
        type="tel"
        placeholder="Please enter the mobile phone"
      />
      <van-field
        @click="startCityPop"
        class="city"
        v-model="city"
        label="City/District"
        right-icon="arrow"
        placeholder="Please select the city,district"
        readonly
      />
      <van-field
        class="address"
        v-model="address"
        label="Address"
        placeholder="Please enter detailed address"
      />

      <van-cell
        class="mark"
        title="Mark"
      >
        <!-- 使用 label 插槽来自定义下方 内容 -->
        <template #label>
          <van-button
            @click="changeType(1)"
            class="location"
            :class="{ mainStyle: type == 1 }"
            plain
            type="primary"
            size="small"
          >Home</van-button>
          <van-button
            @click="changeType(2)"
            class="location"
            :class="{ mainStyle: type == 2 }"
            plain
            type="primary"
            size="small"
          >Company</van-button>
          <van-button
            @click="changeType(3)"
            class="location"
            :class="{ mainStyle: type == 3 }"
            plain
            type="primary"
            size="small"
          >School</van-button>
          <!-- <van-button
            @click="openMarkPop"
            class="imark"
            plain
            type="primary"
            size="small"
          >Add Mark +</van-button> -->
        </template>
      </van-cell>
      <van-cell
        v-if="isFromMain"
        class="isAddBook"
        center
        title="Add to address book"
      >
        <template #right-icon>
          <van-switch
            v-model="isAddBook"
            size="24"
          />
        </template>
      </van-cell>
    </div>

    <div class="bottom">
      <van-button
        @click="save"
        type="primary"
        size="large"
      >Save</van-button>
    </div>
    <cityPop
      :show="isCityPop"
      @closePop="closePop"
      @getCityData="getCityData"
    ></cityPop>
    <markPop
      :show="isMarkPop"
      @closePop="closePop"
      @getMarkData="getMarkData"
    ></markPop>
  </div>
</template>
<script>
import NavBar from '@/components/NavBar'
import cityPop from '@/components/pop/cityPop.vue'
import markPop from '@/components/pop/markPop.vue'
import { Address, validata } from '@/model/address.js'
import { matchPhone } from '../../utils/validate.js'
import { addAddress } from 'api/user.js'
import LocalStorge from '../../model/localStorage.js'
import { Toast } from 'vant'
import LocalStorage from '../../model/localStorage.js'

export default {
  name: 'editItem',
  components: {
    NavBar,
    cityPop,
    markPop
  },

  methods: {
    getMarkData() {
      alert('markData')
    },
    getCityData(text, data) {
      this.city = text
      const { provinceId, cityId, areaId } = data
      this.provinceId = provinceId
      this.cityId = cityId
      this.zoneId = areaId
      // console.log(data)
      // alert(text)
    },
    closePop() {
      this.isCityPop = false
      this.isMarkPop = false
    },
    goBack() {
      // this.$router.go(-2)
      this.$router.replace({
        path: '/main'
      })
    },
    startCityPop() {
      // alert('cityPop')
      this.isCityPop = true
    },
    openMarkPop() {
      this.isMarkPop = true
    },
    saveEdit() {
      // console.log('新增')
      //  name,
      //   phone,
      //   address,
      //   provinceId,
      //   cityId,
      //   zoneId,
      //   consumerId,
      //   addressId,
      //   type,
      //   location,
      //   provinceName,
      //   cityName,
      //   zoneName
      let data = JSON.parse(
        JSON.stringify({
          name: this.name,
          phone: this.phone,
          address: this.address,
          provinceId: this.provinceId,
          cityId: this.cityId,
          zoneId: this.zoneId,
          consumerId: LocalStorage.get('token') ? JSON.parse(this.$store.state.app.userInfo).consumerId : '',
          addressId: this.addressId,
          type: this.type,
          doType: this.doType,
          city: this.city
        })
      )
      // console.log(data)

      if (this.who == 'ConsignorInfo') {
        this.$store.dispatch('setConsignorInfo', JSON.stringify(data))
      } else if (this.who == 'ReceiverInfo') {
        this.$store.dispatch('setReceiverInfo', JSON.stringify(data))
      }

      const { name, phone, address, provinceId, cityId, zoneId, consumerId, addressId, type, doType } = data

      const addressInstance = new Address(
        name,
        phone,
        address,
        provinceId,
        cityId,
        zoneId,
        consumerId,
        addressId,
        type,
        doType
      )
      // console.log(addressInstance)
      // let token = this.$store.state.app.token
      if (validata(addressInstance, Address)) {
        let data = addressInstance._getData()
        addAddress(data)
          .then(res => {
            Toast.success({
              message: res.message
            })
            setTimeout(() => {
              this.$router.go(-1)
            }, 1000)
          })
          .catch(err => {
            Toast.fail({
              message: err
            })
          })
      }
    },
    save() {
      console.log('dotype', this.doType)
      if (matchPhone(this.phone)) {
        if (this.pageId == 1) {
          if (this.isAddBook) {
            this.saveEdit()
          } else {
            // console.log('555')
            // let data = JSON.parse(
            //   JSON.stringify({
            //     name: this.name,
            //     phone: this.phone,
            //     address: this.address,
            //     provinceId: this.provinceId,
            //     cityId: this.cityId,
            //     zoneId: this.zoneId,
            //     consumerId: LocalStorage.get('token') ? JSON.parse(this.$store.state.app).userInfo.consumerId : '',
            //     addressId: this.addressId,
            //     type: this.type,
            //     doType: this.doType
            //   })
            // )
            let data = {
              name: this.name,
              phone: this.phone,
              address: this.address,
              provinceId: this.provinceId,
              cityId: this.cityId,
              zoneId: this.zoneId,
              city: this.city,
              consumerId: LocalStorage.get('token') ? JSON.parse(this.$store.state.app.userInfo).consumerId : '',
              addressId: this.addressId,
              type: this.type,
              doType: this.doType
            }
            console.log('xx', data)
            if (this.who == 'ConsignorInfo') {
              this.$store.dispatch('setConsignorInfo', JSON.stringify(data))
            } else if (this.who == 'ReceiverInfo') {
              this.$store.dispatch('setReceiverInfo', JSON.stringify(data))
            }

            setTimeout(() => {
              this.$router.replace({
                path: '/main'
              })
            }, 300)
          }
        } else {
          this.saveEdit()
        }
      }else{
        Toast.fail({
          message:"Phone Error!"
        })
      }
    },
    do(str) {
      // console.log(str)
      //通讯录的 编辑
      const {
        name,
        phone,
        address,
        provinceId,
        cityId,
        zoneId,
        consumerId,
        addressId,
        type,
        location,
        provinceName,
        cityName,
        zoneName
      } = JSON.parse(str)
      this.name = name
      this.phone = phone
      this.address = address
      this.city = provinceName + '  ' + cityName + '  ' + zoneName
      this.type = type
      this.provinceId = provinceId
      this.cityId = cityId
      this.zoneId = zoneId
      this.consumerId = consumerId
      this.addressId = addressId
    },
    do1(str) {
      // 从首页 input 中带来的
      // console.log('str', str)
      const { name, phone, address, provinceId, city, cityId, zoneId, consumerId, addressId, type } = JSON.parse(str)
      this.name = name
      this.phone = phone
      this.address = address
      this.city = city
      this.type = type
      this.provinceId = provinceId
      this.cityId = cityId
      this.zoneId = zoneId
      this.consumerId = consumerId
      this.addressId = addressId
    },
    handleData(str) {
      let key = str.split(';')[0]
      // console.log(key)
      if (key == 'ConsignorInfo') {
        this.who = 'ConsignorInfo'
        // if (str.split(';')[1] == '{}') {
        //   this.isFromMain = false
        // }
        this.do1(str.split(';')[1])
      } else if (key == 'ReceiverInfo') {
        this.who = 'ReceiverInfo'
        // if (str.split(';')[1] == '{}') {
        //   this.isFromMain = false
        // }
        this.do1(str.split(';')[1])
      }
    },
    changeType(num) {
      this.type = num
    }
  },
  data() {
    return {
      pageId: '',
      doType: '',
      title: 'Add Address',
      name: '',
      phone: '',
      city: '', //三级地址
      address: '', //填写的地址
      isFromMain: true,
      isAddBook: false,
      isCityPop: false,
      isMarkPop: false,
      type: '', //家 公司
      provinceId: '',
      cityId: '',
      zoneId: '',
      consumerId: '',
      addressId: '',
      who: ''
    }
  },
  created() {
    // alert(this.$route.params.id)
    let pageId = this.$route.params.id
    this.pageId = pageId
    /**
     * id
     * 1 : 首页显示的编辑
     * 2 : 通讯录item 的 点击编辑
     * 3 : 通讯录底部 的 add address 按钮
     */
    switch (pageId) {
      case 1:
        if (LocalStorage.get('token')) {
          this.isFromMain = true
        } else {
          //  这里的 意思  是 没登陆时 不显示 新增地址 checkBox
          this.isFromMain = false
        }
        this.handleData(this.$route.params.str)
        this.doType = 'edit'
        break
      case 2:
        this.isFromMain = false
        this.do(this.$route.params.str)
        this.who = this.$route.params.who
        // console.log('who', this.who)
        this.doType = 'edit'
        break
      case 3:
        this.isFromMain = false
        this.consumerId = JSON.parse(this.$store.state.app.userInfo).consumerId
        this.doType = ''
        break
      case undefined:
        this.$router.go(-2)
        break
      //  default:
    }
  },
  mounted() {}
}
</script>
<style lang="scss" scoped>
@import './editItem.scss';
</style>
